package com.ewanghuiju.app.ui.shopmail.activity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.shopmail.CreateShareContract;
import com.ewanghuiju.app.model.bean.response.CreateShareResponBean;
import com.ewanghuiju.app.presenter.shopmail.CreateSharePresenter;
import com.ewanghuiju.app.test.bean.TestBean;
import com.ewanghuiju.app.ui.shopmail.adapter.CreateShareAdapter;
import com.ewanghuiju.app.util.GlideSimpleLoader;
import com.ewanghuiju.app.util.PermissionUtil;
import com.ewanghuiju.app.util.ToastUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.util.sharemoreimage.ShareManager;
import com.ewanghuiju.app.util.sharemoreimage.Tools;
import com.gyf.immersionbar.ImmersionBar;
import com.sch.share.Options;
import com.sch.share.WXShareMultiImageHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 创建分享
 * @time 2020/2/19
 */
public class CreateShareActivity extends BaseActivity<CreateSharePresenter> implements CreateShareContract.View {


    @BindView(R.id.toolbar)
    RelativeLayout toolbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_store_name)
    TextView tvStoreName;
    @BindView(R.id.view_line_one)
    View viewLineOne;
    @BindView(R.id.tv_imags_title)
    TextView tvImagsTitle;
    @BindView(R.id.view_line_two)
    View viewLineTwo;
    @BindView(R.id.tv_share_wenan)
    TextView tvShareWenan;
    @BindView(R.id.tv_baocun)
    TextView tvBaocun;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.tv_friend)
    TextView tvFriend;
    @BindView(R.id.tv_qq)
    TextView tvQq;
    @BindView(R.id.tv_wb)
    TextView tvWb;

    private GlideSimpleLoader glideSimpleLoader;

    private ShareManager shareManager;

    private String[] stringItem = {"https://gd2.alicdn.com/imgextra/i1/2259324182/TB2sdjGm0BopuFjSZPcXXc9EpXa_!!2259324182.jpg",
            "http://img4.tbcdn.cn/tfscom/i1/2259324182/TB2ISF_hKtTMeFjSZFOXXaTiVXa_!!2259324182.jpg",
            "http://img2.tbcdn.cn/tfscom/i1/2259324182/TB2NAMmm00opuFjSZFxXXaDNVXa_!!2259324182.jpg","https://img.zcool.cn/community/0152c75b7d26f6a80120577d14b536.JPG@3000w_1l_2o_100sh.jpg"
    ,"https://img.zcool.cn/community/01dd945e5baa6ca80120a895072bc8.jpg","https://img.zcool.cn/community/01f3965e5baa7ca80121651832611a.jpg"};
    private List<String> stringList = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.activity_create_share;
    }

    @Override
    protected void initEventAndData() {
        glideSimpleLoader = new GlideSimpleLoader();
        glideSimpleLoader.onCreate(mContext);

        GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{Color.parseColor("#DA291C"), Color.parseColor("#FFFFFF")});
        viewLineOne.setBackground(gradientDrawable);
        viewLineTwo.setBackground(gradientDrawable);

        for (int i = 0; i < stringItem.length; i++) {
            stringList.add(stringItem[i]);
        }
        intImageList();
    }

    private void intImageList() {
        List<CreateShareResponBean> createShareResponBeans = TestBean.getCreateShareResponBeanList(6);
        List<String> picList = new ArrayList<>();
        for (int i = 0; i < createShareResponBeans.size(); i++) {
            picList.add(createShareResponBeans.get(i).getUrl());
        }
        CreateShareAdapter createShareAdapter = new CreateShareAdapter(R.layout.item_create_share);
        createShareAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                CreateShareResponBean  itemBean =  (CreateShareResponBean)adapter.getItem(position);
//                if(itemBean.getIsChecked()==0){
//                    itemBean.setIsChecked(1);
//                }else{
//                    itemBean.setIsChecked(0);
//                }
//                adapter.notifyItemChanged(position,itemBean);

                if (glideSimpleLoader != null) {
                    glideSimpleLoader.showUrl(picList, position);
                }
            }
        });
        GridLayoutManager layoutManager = new GridLayoutManager(mContext, 3);
        layoutManager.setSmoothScrollbarEnabled(true);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(createShareAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setFocusable(false);
        createShareAdapter.setNewData(createShareResponBeans);
    }

    @OnClick({R.id.iv_back, R.id.tv_baocun, R.id.tv_wx, R.id.tv_friend})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        PermissionUtil.requestPermissionForActivity(this, new PermissionUtil.IPermissionListener() {
            @Override
            public void permissionGranted() {

                switch (view.getId()) {
                    case R.id.iv_back:
                        finish();
                        break;
                    case R.id.tv_baocun:
                        ToastUtil.show("请稍后");
                        share(0, "", "wchat");
                        break;
                    case R.id.tv_wx:
                        ToastUtil.show("请稍后");
                        shareToSession();
                        break;
                    case R.id.tv_friend:
//                ToastUtil.show( "请稍后");
//                share(1,"微信分享朋友圈的说明","wchat");
                        shareToTimeline();
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void permissionDenied() {
                ToastUtil.show("权限被拒绝,请设置应用权限");
            }
        }, "权限被拒绝,请设置应用权限", PermissionUtil.scan_permissions);

    }

    // 分享给好友。
    private void shareToSession() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

//            addSubscribe(mDataManager.fetchWelcomeInfo(RES)
//                    .compose(RxUtil.<WelcomeBean>rxSchedulerHelper())
//                    .subscribe(new Consumer<WelcomeBean>() {
//                        @Override
//                        public void accept(WelcomeBean welcomeBean) {
//                            mView.showContent(welcomeBean);
//                            startCountDown();
//                        }
//                    }, new Consumer<Throwable>() {
//                        @Override
//                        public void accept(Throwable throwable) {
//                            mView.jumpToMain();
//                        }
//                    })
//            );

        }else{


        }

        ArrayList<File> fileList = new ArrayList<>();
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        for (String str : stringList) {
            fileList.add(new File(str));
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (String str : stringList) {
                        Bitmap  bitmap = Glide.with(mContext)
                                .asBitmap()
                                .load(str)
                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                .get();
                        if(bitmap!=null){
                            bitmaps.add(bitmap);
                        }
                    }
                    Bitmap[] bitmapArray = new Bitmap[bitmaps.size()];
                    WXShareMultiImageHelper.shareToSession(mContext, bitmaps.toArray(bitmapArray), "分享的文案");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    // 分享到朋友圈。
    private void shareToTimeline() {
        ArrayList<File> fileList = new ArrayList<>();
        ArrayList<Bitmap> bitmaps = new ArrayList<>();
        for (String str : stringList) {
            fileList.add(new File(str));
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (String str : stringList) {
                        Bitmap  bitmap = Glide.with(mContext)
                                .asBitmap()
                                .load(str)
                                .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                .get();
                        if(bitmap!=null){
                            bitmaps.add(bitmap);
                        }
                    }
                    Bitmap[] bitmapArray = new Bitmap[bitmaps.size()];
                    Options options = new Options();
                    options.setText("分享分享");
                    WXShareMultiImageHelper.shareToTimeline(mContext, bitmaps.toArray(bitmapArray), options);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    //===============================================================

    private boolean isShareImg = false;

    private void share(int i, String s, String mType) {
        isShareImg = true;
        shareManager = new ShareManager(mContext);
        shareManager.setShareImage(i, stringList, s, mType);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(toolbar)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    public void onBackPressedSupport() {
        if (!glideSimpleLoader.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (isShareImg) {
            isShareImg = false;
            File file = new File(Environment.getExternalStorageDirectory() + "/shareImg/");
            Tools.deletePic(file);
        }
    }

    @Override
    protected void onDestroy() {
        WXShareMultiImageHelper.clearTmpFile(this);
        super.onDestroy();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showContent(String list) {

    }

    @Override
    public void showMoreContent(String list) {

    }
}
